from gatherers import *
from time import sleep
from threading import Thread
from linux_analyser.utils.utils import *
import os
from linux_analyser.utils.stoppable_thread import StoppableThread
from linux_analyser.utils.filelock import FileLock

class GathererGovernor(StoppableThread):
    "class managing gatherers"

    def __init__(self, cpu = False, cpu_interval = None, cpu_threshold = None, cpu_username = None,
    cpu_name = None, ram = False, ram_interval = None, ram_threshold = None, ram_username = None,
    ram_name = None, run_time = None, filename = "../tmp/test.csv"):
        StoppableThread.__init__(self)

        lock = FileLock(filename, timeout=5)
        
        cpu_options = {"interval": cpu_interval, "threshold": cpu_threshold, "username": cpu_username, "name": cpu_name, "filename" : filename, "lock": lock}
        cpu_options = dict(not_null_items(cpu_options))

        ram_options = {"interval": ram_interval, "threshold": ram_threshold, "username": ram_username, "name": ram_name, "filename" : filename, "lock": lock}
        ram_options = dict(not_null_items(ram_options))        
        
        self.gatherers = []
        if cpu:
            self.gatherers.append(CPUGatherer(**cpu_options))
        if ram:
            self.gatherers.append(RAMGatherer(**ram_options))
            
        self.run_time = run_time
        self.filename = filename
        self.cpu = cpu
        self.ram = ram
        self.cpu_name = cpu_name
        
    def run(self):
        ""
        f = open(self.filename, 'w')
        f.write(self.metadata())
        f.close()        
        [gatherer.start() for gatherer in self.gatherers]
        if self.run_time != None:
            sleep(self.run_time)
        else:
            while True:
                sleep(1)
                if self.stopped():
                    break
        self.end_gracefully()

    def end_gracefully(self):
        print "Governor is stopping gatherer threads.."
        [gatherer.stop() for gatherer in self.gatherers]
        [gatherer.join() for gatherer in self.gatherers]
        print "Governor has ended gracefully!"    

    def metadata(self):
        ""
        resources = []
        if self.cpu:
            resources.append("procesor")
        if self.ram:
            resources.append("pamiec")
        resources = ", ".join(resources)
        return "%s;%s;%s\n" % ("procesy", self.cpu_name, resources)
